import { Staff, StaffService } from "@mallfoundry/store/staff"
import { Card, Col, message as antMessage, Row } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { useHistory, useParams } from "react-router-dom"
import Page from "../../../components/page"
import { messageError } from "../../../utils/reason"
import StaffForm from "./staff-form"

export default function StaffNew() {
  const { storeId } = useParams<{ storeId: string }>()
  const history = useHistory()
  const [loading, setLoading] = useState(false)

  function finish(values: Staff) {
    setLoading(true)
    StaffService.addStaff(values)
      .then(() => {
        antMessage.success("添加成功")
      })
      .then(() => history.goBack())
      .catch(messageError)
      .finally(() => setLoading(false))
  }

  return (
    <div>
      <Page.Header title="添加员工" ghost={false}/>
      <Page.Content>
        <Card>
          <Row>
            <Col span={24}>
              <StaffForm
                loading={loading}
                staff={_.assign(new Staff(), { storeId })}
                onFinish={finish}
                onCancel={() => history.push(`/stores/${storeId}/staffs`)}/>
            </Col>
          </Row>
        </Card>
      </Page.Content>
    </div>
  )
}
